package com.kaifamiao.base.Demo20210926;

import java.io.*;

/**
 * @author lucien-ma
 * @date 2021/9/26
 * @apiNote
 */
public class Demo01 {

    /**
     * 转换文件的编码方式
     * @param source 要转换的源文件
     * @param target 转换后另存的文件
     * @param sEncoding 源文件的编码方式
     * @param tEncoding 另存文件的编码方式
     */
    public static void encodingConversion(File source, File target, String sEncoding, String tEncoding) {
        InputStream in = null;
        InputStreamReader inputStreamReader = null;
        OutputStream out = null;
        OutputStreamWriter outputStreamWriter = null;
        char[] chars = new char[1024];
        try {
            in = new FileInputStream(source);
            inputStreamReader = new InputStreamReader(in, sEncoding);
            out = new FileOutputStream(target);
            outputStreamWriter = new OutputStreamWriter(out,tEncoding);
            int length = -1;
            while ((length = inputStreamReader.read(chars)) != -1) {
                outputStreamWriter.write(chars, 0, length);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStreamWriter.close();
                out.close();
                inputStreamReader.close();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static void encodingConversion(String sourcePath, String targetPath, String sEncoding, String tEncoding) {
        encodingConversion(new File(sourcePath), new File(targetPath), sEncoding, tEncoding);
    }

    /**
     * 将 gbk 编码文件转换为 utf8
     * @param source
     * @param target
     */
    public static void GBKToUTF8(File source, File target) {
        encodingConversion(source, target, "GBK", "UTF-8");
    }

    public static void GBKToUTF8(String source, String target) {
        GBKToUTF8(new File(source), new File(target));
    }

    public static void main(String[] args) {
        GBKToUTF8("E:/test/guanju_gbk.txt",
                "E:/test/guanju_utf8.txt");
    }
}
